<template>
    <h1>3D</h1>
    <div id="three-container"></div>
</template>

<script setup>
import { onMounted } from 'vue';
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// ✅ 添加 OrbitControls
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// 场景、相机、渲染器
const scene = new THREE.Scene();
let camera, renderer, controls; // ✅ 声明 controls

onMounted(() => {
    initThree();
    load3d();
});

// 初始化 Three.js
function initThree() {
    // 相机
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 10;

    // 渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);

    // 把渲染器添加到 #three-container
    const container = document.getElementById('three-container');
    container.appendChild(renderer.domElement);

    // ✅ 创建 OrbitControls
    controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true; // 平滑阻尼
    controls.dampingFactor = 0.1;
    controls.screenSpacePanning = true; // 更自然的平移
    controls.maxDistance = 5000;         // 限制最大缩放距离
    controls.minDistance = 1;          // 限制最小缩放距离

    // 添加灯光（只加一次）
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
    const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
    directionalLight.position.set(1, 1, 1);
    scene.add(ambientLight, directionalLight);

    // 启动渲染循环
    animate(); // ✅ 调用 animate
}

// 动画循环 ✅ 修复：不要嵌套
function animate() {
    requestAnimationFrame(animate);
    controls.update(); // ✅ 更新控制器
    renderer.render(scene, camera);
}

// 加载模型
function load3d() {
    const loader = new GLTFLoader();

    loader.load(
        '/3d/dm_book.glb',
        (gltf) => {
            console.log('✅ 模型加载成功');

            // 强制双面渲染
            gltf.scene.traverse((child) => {
                if (child.isMesh) {
                    child.material.side = THREE.DoubleSide;
                    child.material.transparent = false;
                    child.material.opacity = 1;
                }
            });

            // 设置位置和缩放
            gltf.scene.position.set(0, 0, 0);
            gltf.scene.scale.set(10, 10, 10);

            // 添加坐标轴（辅助线）
            scene.add(new THREE.AxesHelper(10));

            // ✅ 注意：灯光已经在 initThree 中添加，这里不要再重复添加！

            // 自动对焦模型（可选）
            const box = new THREE.Box3().setFromObject(gltf.scene);
            const center = box.getCenter(new THREE.Vector3());
            camera.lookAt(center);

            scene.add(gltf.scene);
        },
        undefined,
        (error) => {
            console.error('❌ 加载失败:', error);
        }
    );
}
</script>

<style scoped>
#three-container {
    width: 100%;
    height: auto;
    background: #000;
    position: relative;
    overflow: hidden;
}

h1 {
    color: white;
    text-align: center;
}
</style>